# coding=utf-8
import os
import random
import datetime
import uuid

from django.conf import settings
from django.http.response import HttpResponse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.shortcuts import RequestContext
from django.template import loader, Context, Template
from django.core.urlresolvers import reverse

from xls_demo.forms.xlsform import *
from xls_demo.db import models
from xls_demo.utils import xlrd
from xls_demo.utils import xlwt
from xls_demo.utils import decorator
from xls_demo.utils import create_failure_dict
from xls_demo.utils import create_success_dict

def index(request):
    try:
        user = session.get_user(request)
        if user.id:
            template = loader.get_template('index.html')
            context = Context({
                'username':user.username,
                'realname':user.realname})
        else:
            template = loader.get_template('index.html')
            context = Context()
    except:
        template = loader.get_template('index.html')
        context = Context()


    return HttpResponse(template.render(context))


def add(request):
    if request.method == 'POST':
        form = xlsForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/new/')
    else:
        form = xlsForm(initial={
            'a':random.sample('abcdefghijklmnopqrstuvwxyz',5),
            'b':datetime.datetime.now().strftime('%S'),
            'c':str(random.random())[:4],
            'd':datetime.datetime.now()
        })
    return render_to_response('index.html', {'form': form},
                            context_instance=RequestContext(request))

def export(request):
    data = models.xls.objects.all()
    records = data.values('a', 'b', 'c', 'd')
    title = u'xls_demo'

    xls = xlwt.Workbook(encoding='utf-8')
    sheet = xls.add_sheet(title)

    header = ['A', 'B', 'C', 'D']
    for i in range(len(header)):
        sheet.write(0, i, header[i].decode('utf-8'))
    row = 1
    for record in records:
        sheet.write(row, 0, record['a'])
        sheet.write(row, 1, record['b'])
        sheet.write(row, 2, record['c'])
        sheet.write(row, 3, record['d'])
        row += 1

    cached_id = str(uuid.uuid1())
    tmp_file = os.path.join(settings.CACHE_TMP_ROOT, cached_id)
    xls.save(tmp_file)
    filename = u'%s.xls' % title

    url = reverse('download',kwargs={'cached_id': cached_id, 'name': filename})
    return HttpResponseRedirect(url)

def importer(request):
    pass


@decorator.file_response
def xls_download(request, *args, **kwargs):
    cached_id = kwargs.get('cached_id')
    if cached_id:
        tmp_file = os.path.join(settings.CACHE_TMP_ROOT, cached_id)
        if os.path.exists(tmp_file):
            name = kwargs.get('name', '%s.xls' % cached_id)
            return create_success_dict(path=tmp_file, name=name)

    return HttpResponseRedirect('/')

def register(request):
    if request.method == 'POST':
        form = userForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/thanks')
    else:
        form = userForm(initial={
            'username':''.join(random.sample('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',3)),
            'password':''.join(random.sample('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',5)),
            'realname':u'王大锤',
            'mobile':'',
            'qq':'',
            'email':''
        })
    return render_to_response('index.html', {'form': form},
                            context_instance=RequestContext(request))

def thanks(request):
    return HttpResponseRedirect('/')

def login(request):
    if request.method == 'POST':
            form = UserLoginForm(request.POST)
            if form.is_valid():
                username = request.POST.get('username', False)
                password = request.POST.get('password', False)
                if username and password:
                    try:
                        user = models.user.objects.get(username=username, password=password)
                        if user.id:
                            session.user = user.id
                            return create_success_dict()
                        return create_failure_dict()
                    except:
                        return create_failure_dict()
    else:
        form = UserLoginForm(initial={
            'username':'username',
            'password':'password'
        })
    return render_to_response('index.html', {'form': form}, context_instance=RequestContext(request))





